package com.google.code.roledroid;

import java.io.File;

import com.google.code.roledroid.CharacterDBHelper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
import android.test.mock.MockContext;

public class DatabaseTest extends AndroidTestCase {

	CharacterDBHelper helper;
	private SQLiteDatabase	db;

	protected void setUp() throws Exception {
		super.setUp();
		db = SQLiteDatabase.create(null);
		Context context = new MockContext()
		{
			@Override
			public SQLiteDatabase openOrCreateDatabase(String file, int mode,
					SQLiteDatabase.CursorFactory factory)
			{
				return db;
			}
			@Override
			public File getDatabasePath(String name)
			{
				return new File("test");
			}
		};
		helper = new CharacterDBHelper(context);
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		db.close();
	}

	// Helper function
	int getRowsCount()
	{
		return helper.getAllRows().getCount();
	}

	// Helper function
	String getRowName(long id)
	{
		return helper.fetchRow(id).name;
	}

	public void testCreateRow() {
		helper.createRow("TEST");

		assertEquals(1, getRowsCount());
	}

	public void testDeleteRow() {	
		long id = helper.createRow("TEST");
		assertEquals(1,getRowsCount());

		helper.deleteRow(id);
		assertEquals(0,getRowsCount());

		// TODO: Improve that test with multiple insertions to see if the deleted row is the right one
	}

	public void testUpdateRow() {
		String origin = "TEST";
		String update = "UPDATED";
		long id = helper.createRow(origin);
		assertEquals(origin,this.getRowName(id));

		helper.updateRow(id, update);
		assertEquals(update,this.getRowName(id));
	}

}
